package com.controller;


import com.entity.BUser;
import com.entity.table.BUserTableDef;
import com.mybatisflex.core.query.QueryWrapper;
import com.service.BUserService;
import com.service.impl.BUserServiceImpl;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class LoginController {
    @Autowired
    BUserServiceImpl bUserService;
//    FUserMapper userMapper;
    @GetMapping("/login")
    public String toLoginPage(){
        return "client/login";
    }
    @PostMapping("/toLogin")
    public String login(BUser user, HttpSession httpSession, Model model){
        QueryWrapper query = QueryWrapper.create()
                .where(BUserTableDef.B_USER.USERNAME.eq(user.getUsername()))
                .and(BUserTableDef.B_USER.PASSWORD.eq(user.getPassword()));
        BUser bUser = bUserService.getOne(query);
        //userMapper.userLogin(user);
        if (bUser!=null){
            httpSession.setAttribute("user",bUser);
            model.addAttribute("user",bUser);//返回数据给前端页面
            //跳转到主页面
//                return "redirect:/";//登录成功跳转到首页链接
           return "client/index";
        }
        else {
            model.addAttribute("msg","账号或密码错误，请重新输入！");
            return "client/login";
        }
    }
    @GetMapping("/logout")
    public String logout( HttpSession httpSession){
        httpSession.removeAttribute("user");
        return "client/login";
    }
}
